package com.tanhua.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.tanhua.properties.AliyunSmsProperties;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import org.apache.commons.lang3.RandomUtils;


/**
 * @author liuyp
 * @date 2021/06/09
 */
public class AliyunSmsTemplate {
    private AliyunSmsProperties properties;

    public AliyunSmsTemplate(AliyunSmsProperties properties) {
        this.properties = properties;
    }

    /**
     * 发送短信
     *
     * @param mobile 手机号
     * @return 发送的验证码
     */
    public String sendSms(String mobile) {

        try {
            int code = RandomUtils.nextInt(100000, 1000000);

            Config config = new Config()
                    .setAccessKeyId(properties.getAccessKeyId())
                    .setAccessKeySecret(properties.getAccessKeySecret());
            // 访问的域名
            config.endpoint = properties.getEndpoint();
            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(properties.getSignName())
                    .setTemplateCode(properties.getTemplateCode())
                    .setTemplateParam("{\"code\": \"" + code + "\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSms(sendSmsRequest);

            if ("OK".equals(response.getBody().getCode())) {
                //如果发送短信成功了，返回验证码值
                return String.valueOf(code);
            }else{
                //发送短信失败了
                System.out.println(response);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
